package com.yunshipei.ui.fragment;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.yunshipei.enterplorer.R;
import com.yunshipei.model.YspEvent;

import java.util.ArrayList;
import java.util.List;

import io.rong.common.RLog;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationListFragment;
import io.rong.imkit.model.Event;
import io.rong.imkit.model.UIConversation;
import io.rong.imkit.widget.adapter.ConversationListAdapter;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

/**
 * Created by cike on 16/8/9.
 */
public class YspConversationListFragment extends ConversationListFragment {
    private final String TAG = YspConversationListFragment.class.getSimpleName();
    private ArrayList<Conversation.ConversationType> mSupportConversationList = new ArrayList<>();
    private ConversationListAdapter mAdapter;
    private ListView listView;

    public static YspConversationListFragment newInstance(Context context) {
        YspConversationListFragment conversationListFragment = new YspConversationListFragment();
        Uri uri = Uri.parse("rong://" + context.getApplicationInfo().packageName).buildUpon()
                .appendPath("conversationlist")
                .appendQueryParameter(Conversation.ConversationType.PRIVATE.getName(), "false") //设置私聊会话是否聚合显示
                .appendQueryParameter(Conversation.ConversationType.GROUP.getName(), "false")//群组
                .appendQueryParameter(Conversation.ConversationType.DISCUSSION.getName(), "false")//讨论组
                .appendQueryParameter(Conversation.ConversationType.APP_PUBLIC_SERVICE.getName(), "false")//应用公众服务。
                .appendQueryParameter(Conversation.ConversationType.PUBLIC_SERVICE.getName(), "false")//公共服务号
                .appendQueryParameter(Conversation.ConversationType.SYSTEM.getName(), "false")//系统
                .build();
        conversationListFragment.setUri(uri);
        return conversationListFragment;
    }

    public static YspConversationListFragment getInstance() {
        return new YspConversationListFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        listView = (ListView) view.findViewById(R.id.rc_list);
        final TextView textView = (TextView) view.findViewById(R.id.rc_empty_tv);
//        textView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                EventBus.getDefault().post(new Event.AgainGetContactsEvent());
//                textView.setText(io.rong.imkit.R.string.rc_group_list_pulling_prompt);
//                textView.setTextColor(Color.parseColor("#999999"));
//            }
//        });
        return view;
    }

    public void onEventMainThread(Event.ConnectEvent event) {
        LinearLayout emptyView = (LinearLayout) listView.getEmptyView();
        TextView textView = (TextView) emptyView.findViewById(io.rong.imkit.R.id.rc_empty_tv);
        textView.setText(RongContext.getInstance().getResources().getString(io.rong.imkit.R.string.rc_conversation_list_empty_prompt));
    }

    public void onEventMainThread(YspEvent.ConnectEvent event) {
        refreshConversationList();
    }

    public void onEventMainThread(YspEvent.RefreshMainAdapterEvent event) {
        if (listView != null && listView.getAdapter() != null) {
            ((ConversationListAdapter) listView.getAdapter()).notifyDataSetChanged();
        } else {
            Log.e("refresh Main Adapter", "list is null");
        }
    }

    //刷新会话列表
    private void refreshConversationList() {
        if (listView != null && listView.getAdapter() != null) {
            RongIM.getInstance().getConversationList(mCallback);
        } else {
            Log.e(TAG, "list is null or adapter is null");
        }
    }

    private RongIMClient.ResultCallback<List<Conversation>> mCallback = new RongIMClient.ResultCallback<List<Conversation>>() {
        @Override
        public void onSuccess(List<Conversation> conversations) {

            if (listView != null && listView.getAdapter() != null) {
                mAdapter = (ConversationListAdapter) listView.getAdapter();
                RLog.d(TAG, "ConversationListFragment initFragment onSuccess callback : list = " +
                        (conversations != null ? conversations.size() : "null"));

                if (mAdapter != null && mAdapter.getCount() != 0) {
                    mAdapter.clear();
                }

                if (conversations == null || conversations.size() == 0) {
                    if (mAdapter != null)
                        mAdapter.notifyDataSetChanged();
                    return;
                }

                if (mAdapter == null)
                    mAdapter = new ConversationListAdapter(RongContext.getInstance());
                makeUiConversationList(conversations);

                if (listView != null && listView.getAdapter() != null) {
                    mAdapter.notifyDataSetChanged();
                }

            }

        }

        @Override
        public void onError(RongIMClient.ErrorCode e) {
            RLog.d(TAG, "ConversationListFragment initFragment onError callback, e=" + e);
            if (e.equals(RongIMClient.ErrorCode.IPC_DISCONNECT)) {

            }
        }
    };

    private void makeUiConversationList(List<Conversation> conversationList) {
        UIConversation uiCon;

        //获取到的conversationList排序规律：首先是top会话，按时间顺序排列。然后非top会话也是按时间排列。
        for (Conversation conversation : conversationList) {
            Conversation.ConversationType conversationType = conversation.getConversationType();
//            boolean gatherState = RongContext.getInstance().getConversationGatherState(conversationType.getName());
            boolean gatherState = false;
            int originalIndex = mAdapter.findPosition(conversationType, conversation.getTargetId());//判断该条会话是否已经在会话列表里建立。

            uiCon = UIConversation.obtain(conversation, gatherState);
            if (originalIndex < 0) {
                mAdapter.add(uiCon);
            }
            refreshUnreadCount(uiCon.getConversationType(), uiCon.getConversationTargetId());
        }
    }

    private void refreshUnreadCount(final Conversation.ConversationType type, final String targetId) {
        boolean gatherState = false;
//        gatherState = RongContext.getInstance().getConversationGatherState(type.getName());
        if (gatherState) {
            RongIM.getInstance().getUnreadCount(new RongIMClient.ResultCallback<Integer>() {
                @Override
                public void onSuccess(Integer count) {
                    int curPos = mAdapter.findPosition(type, targetId);
                    if (curPos >= 0) {
                        mAdapter.getItem(curPos).setUnReadMessageCount(count);
                        mAdapter.getView(curPos, listView.getChildAt(curPos - listView.getFirstVisiblePosition()), listView);
                    }
                }

                @Override
                public void onError(RongIMClient.ErrorCode e) {
                    System.err.print("Throw exception when get unread message count from ipc remote side!");
                }
            }, type);
        } else {
            RongIM.getInstance().getUnreadCount(type, targetId, new RongIMClient.ResultCallback<Integer>() {
                @Override
                public void onSuccess(Integer integer) {
                    int curPos = mAdapter.findPosition(type, targetId);
                    if (curPos >= 0) {
                        mAdapter.getItem(curPos).setUnReadMessageCount(integer);
                        mAdapter.getView(curPos, listView.getChildAt(curPos - listView.getFirstVisiblePosition()), listView);
                    }
                }

                @Override
                public void onError(RongIMClient.ErrorCode e) {

                }
            });
        }
    }


}
